﻿using System;
using GammaJul.ReSharper.GammaXaml.Highlightings.Xaml;
using GammaJul.ReSharper.GammaXaml.Psi;
using JetBrains.Annotations;
using JetBrains.Application.Progress;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.Bulbs;
using JetBrains.ReSharper.Intentions.Extensibility;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Xaml.Impl.Tree;
using JetBrains.TextControl;
using JetBrains.Util;

namespace GammaJul.ReSharper.GammaXaml.QuickFixes.Xaml {

	/// <summary>
	/// A quick fix that removes an attached setter.
	/// </summary>
	[QuickFix]
	public class RemoveSetterFix : QuickFixBase {
		private readonly DeadCodeSetterHighlightingBase _highlighting;

		public override string Text {
			get {
				return _highlighting is MeaninglessAttachedSetterHighlightingBase
					? "Remove meaningless setter"
					: "Remove redundant setter";
			}
		}

		protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) {
			IPropertySetter propertySetter = _highlighting.PropertySetter;
			IPsiSourceFile sourceFile = propertySetter.GetSourceFile();
			IPsiServices psiServices = propertySetter.GetPsiServices();

			propertySetter.Delete();
			psiServices.MarkAsDirty(sourceFile);

			return null;
		}

		public override bool IsAvailable(IUserDataHolder cache) {
			return _highlighting.IsValid();
		}

		public RemoveSetterFix([NotNull] DeadCodeSetterHighlightingBase highlighting) {
			if (highlighting == null)
				throw new ArgumentNullException("highlighting");

			_highlighting = highlighting;
		}
	}

}